var mongoose = require('mongoose');
const Cate = require('../model/cate.model');
//增
exports.create = function(req, res, next) {
    const cate = new Cate(req.body);
    //实例化对象，req.body代表的事post的数据提交，并且参数从body中获取
    cate.save().then(data => {
        //数据保存，在保存以后将数据用json形式进行输出
        res.json(data);
    });
};
//删
exports.remove = function(req, res, next) {
    var id = req.params.id;
    var ids = [];

    Cate.findOne({ _id: id }, function(err, doc) {
        if (doc) {
            ids = [doc.id];
            doc.getChildren(function(err, docs) {
                var docslength = docs.length
                for (var i = 0; i < docslength; i++) {
                    ids.push(docs[i]._id);
                }
                Cate.remove({ _id: { $in: ids } }).then(data => {
                    res.json({ message: '删除成功' });
                });
            });
        };
    });
}

//改 req.body,req.query,req.params(斜杠....)
exports.update = function(req, res, next) {
    const id = req.params.id;
    //先查找一个id值
    Cate.findByIdAndUpdate(id, { $set: req.body }, { new: false }).then(data => {
        res.json(data);
    });
};

//查
//pid=parentId
function reverseTree(data, pid) {
    var result = [];
    var temp;
    //将数据模型的data转成字符串，再将字符串转成object--->Object就只是一个普通的js的Object
    //原来数据模型中没有的字段无法添加，但转成普通对象就可以了
    var data = JSON.parse(JSON.stringify(data));

    for (var i in data) {
        if (data[i].parentId === pid) {
            result.push(data[i]);
            temp = reverseTree(data, data[i]._id);
            if (temp.length > 0) {
                data[i].children = temp;
            }
        }
    }
    return result;
};

exports.list = function(req, res, next) {
    var type = req.params.type;
    Cate.find({ type: type }, function(err, data) {
        var rpTree = reverseTree(data, null);
        res.json(rpTree);
    });
};